package com.usoft;

import com.usoft.grpc.example.helloworld.GreeterGrpc;
import com.usoft.grpc.example.helloworld.HelloRequest;
import com.usoft.grpc.example.helloworld.HelloResponse;
import io.grpc.ManagedChannel;
import io.grpc.netty.GrpcSslContexts;
import io.grpc.netty.NegotiationType;
import io.grpc.netty.NettyChannelBuilder;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.SslProvider;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

/**
 * Created by xinxingegeya on 16/1/2.
 */
public class GreeterClientTest {
    private static final Logger logger = Logger
        .getLogger(GreeterClientTest.class.getName());

    private String address = "www.helloworld.com:8888";

    private ManagedChannel channel;

    private GreeterGrpc.GreeterBlockingStub greeterBlockingStub;
    private GreeterGrpc.GreeterStub greeterStub;

    @Before
    public void setup() throws IOException {
        // It's a Netty transport.
        NegotiationType negotiationType = NegotiationType.TLS;
        File cert = Utils.loadCert("ca-chain.cert.pem");
        SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient()
            .trustManager(cert);
        sslContextBuilder = GrpcSslContexts.configure(sslContextBuilder,
            SslProvider.JDK);
        SslContext sslContext = sslContextBuilder.build();

        final EventLoopGroup group = new NioEventLoopGroup();
        final Class<? extends io.netty.channel.Channel> channelType = NioSocketChannel.class;
        NettyChannelBuilder builder = NettyChannelBuilder
            .forAddress(Utils.parseSocketAddress(address)).eventLoopGroup(group)
            .channelType(channelType).negotiationType(negotiationType)
            .sslContext(sslContext);

        channel = builder.build();
        greeterBlockingStub = GreeterGrpc.newBlockingStub(channel);
        greeterStub = GreeterGrpc.newStub(channel);
    }

    @After
    public void shutdown() throws InterruptedException {
        channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
    }

    @Test
    public void testGreeter() {
        HelloRequest request = HelloRequest.newBuilder().setName("liyanxin")
            .build();
        HelloResponse resp1 = greeterBlockingStub.sayHello(request);
        HelloResponse resp2 = greeterBlockingStub.sayHello(request);
        HelloResponse resp3 = greeterBlockingStub.sayHello(request);
        HelloResponse resp4 = greeterBlockingStub.sayHello(request);

        System.out.println(resp1.getMessage());
        System.out.println(resp2.getMessage());
        System.out.println(resp3.getMessage());
        System.out.println(resp4.getMessage());
    }

}
